$NG.AllReady(function (page, { useDataIndexChange, useValuesChange, useClick, useUpdateRows }) {
	if (page.oType == "add") {
        getGzZc()
	}
	const mstform = $NG.getCmpApi("p_form_sub_cnt_m");
	const dgrid1 = $NG.getCmpApi("p_form_sub_cnt_d1");
	const dgrid2 = $NG.getCmpApi("p_form_sub_cnt_d2");
	const gridToolbar = $NG.getCmpApi("toolbar_p_form_sub_cnt_d1")
	gridToolbar.getItem('imp').setProps({children:'引用完工上报清单明细'})
	/*const gridToolbar1 = $NG.getCmpApi("toolbar_p_form_sub_cnt_d2")
	gridToolbar1.getItem('imp').setProps({children:'引用分包奖罚单明细'})*/
    useValuesChange(({args})=>{
        console.log(`监听合同变化`,args);
        const _data = args[0]
        getCntMInfoByPhid()
        getPtInfoByPhid_cnt()
        getCntDetil()
    },"p_form_sub_cnt_m.u_cnt_name")

    useValuesChange(({args})=>{
        getCntDetil()
    },"p_form_sub_cnt_m.phid_pc")

    useValuesChange(({args})=>{
        getCntDetil()
    },"p_form_sub_cnt_m.u_js_type")
    //结算清单相关计算
    window.__cache_lsz_d1={}
    window.__cache_lsz_d1_qty={}
    useUpdateRows(({args})=>{
        console.log(`结算清单rows触发`,args);
        const _arr= args[0]
        _arr.forEach((item, index)=>{
            // 本期核定数量
            console.log(!window.__cache_lsz_d1[item.u_cnt_qd_name]||!item.u_cnt_qd_name);
            if(!window.__cache_lsz_d1[item.u_cnt_qd_name]||!item.u_cnt_qd_name||!window.__cache_lsz_d1_qty[item.u_cnt_qd_name]){
                getFbCntJs(item.u_cnt_qd_name,(amt,qty)=>{
                    window.__cache_lsz_d1[item.u_cnt_qd_name] = amt
                    window.__cache_lsz_d1_qty[item.u_cnt_qd_name] = qty
                    item.u_bqhd_qty = ((Number(item.u_bqjl_qty)||0) - (Number(item.u_bq_hjqty))||0)<0?0:((Number(item.u_bqjl_qty)||0) - (Number(item.u_bq_hjqty))||0)
                    item.u_ljhd_qty = ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))<0?0:((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))
                    item.u_bqjs_amt_vat = (Number(item.u_cnt_prc_vat) || 0)*(Number(item.u_bqhd_qty) || 0)
                    item.u_ljjs_amt_vat = Number(amt)+Number(item.u_bqjs_amt_vat)
                    item.u_lj_hjqty = Number(qty)+Number(item.u_bqhd_qty)
                })
            }else{
                item.u_bqhd_qty = ((Number(item.u_bqjl_qty)||0) - (Number(item.u_bq_hjqty))||0)<0?0:((Number(item.u_bqjl_qty)||0) - (Number(item.u_bq_hjqty))||0)
                item.u_ljhd_qty = ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))<0?0:((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))
                item.u_bqjs_amt_vat = (Number(item.u_cnt_prc_vat) || 0)*(Number(item.u_bqhd_qty) || 0)
                item.u_ljjs_amt_vat = (Number(window.__cache_lsz_d1[item.u_cnt_qd_name]) || 0)+(Number(item.u_bqjs_amt_vat) || 0)
                item.u_lj_hjqty = (Number(window.__cache_lsz_d1_qty[item.u_cnt_qd_name]) || 0)+(Number(item.u_bqhd_qty) || 0)
            }
            
        })
        dgrid1.refreshView()
    },"p_form_sub_cnt_d1")
	//获取项目信息
	function getProjectInfo() {
		$NG.execServer(
			"getPtInfoByPhid_cnt",
			{ phid_cnt: mstform.getItem("u_cnt").getValue() },
			function (res) {
				const datas = JSON.parse(res.data)[0].extendObjects;
				console.log(datas);
				$NG.updateState((updater) => {
					updater.data.当前表名.setProps({
						//项目编码
						pc_no: datas.pc_no,
						//项目金额
						approx_contract_fc: datas.approx_contract_fc,
						//计划开工日期
						start_date: datas.start_date,
						//计划完工日期
						end_date: datas.end_date,
						//售前顾问
						u_sqgw: {
							value: datas.user_sqgw_phid,
							label: datas.user_sqgw_name,
						},
						//项目经理
						u_project_manager: {
							value: datas.project_manager_phid,
							label: datas.project_manager_name,
						},
						//事业部
						u_division: {
							value: datas.division_phid,
							label: datas.division_name,
						},
						//组织
						phid_org_phid: {
							value: datas.phid_org_phid,
							label: datas.phid_org_name,
						},
						//区域中心
						u_regional_center: {
							value: datas.regional_center_phid,
							label: datas.regional_center_name,
						},
						//产品线
						user_product_line: {
							value: datas.midwife_phid,
							label: datas.midwife_name,
						},
						//客户名称
						customer: {
							value: datas.customer_id,
							label: datas.customer_name,
						},
						//部门
						u_dept: {
							value: datas.dept_phid,
							label: datas.dept_name,
						},
						//项目类型
						u_pc_type: {
							value: datas.type_phid,
							label: datas.type_name,
						},
						//项目预算组织编码
						budget_org_code: datas.budget_org_no,
						//项目预算组织
						budget_org_phid: {
							value: datas.budget_org_phid,
							label: datas.budget_org_name,
						},
					});
				});
			}
		);
	}
    //获取结算明细
    function getFbCntJs(phid, fun){
        if(!phid||!mstform.getItem("u_cnt_name").getValue()){fun(0);return}
        $NG.execServer("getFbCntJs",{cnt_phid:mstform.getItem("u_cnt_name").getValue(),qd_phid:phid},function(res){
            console.log(`获取累计金额`,mstform.getItem("u_cnt_name").getValue(),phid,res);
            if(res.count==0) {
                fun(0,0)
            }else{
            const _data = JSON.parse(res.data)[0].extendObjects
            fun(_data.total_amt, _data.total_qty)
            }
            dgrid1.refreshView()
        })
    }

	//获取合同信息
    getCntMInfoByPhid()
	function getCntMInfoByPhid() {
        if(!mstform.getItem("u_cnt_name").getValue()) return 
        console.log(`开始获取合同`);
		$NG.execServer(
			"getCntMInfoByPhid",
			{ phid: mstform.getItem("u_cnt_name").getValue() },
			function (res) {
                if(res.count==0) return
				const datas = JSON.parse(res.data)[0].extendObjects;
				console.log(datas);
				$NG.updateState((updater) => {
					updater.data.p_form_sub_cnt_m.setProps({
						u_cnt_no: datas.pcm_no, //合同编码
						u_jsamt_vat: datas.cnt_sum_vat_fc, //合同价税合计
						//合同类型
						pct_id: { value: datas.pct_id, label: datas.pct_name },
						//甲方单位
						u_dept_a: {
							value: datas.customer_id,
							label: datas.customer_name,
						},
						//乙方单位
						u_yf_dept: {
							value: datas.supply_id,
							label: datas.supply_name,
						},
					});
				});
			}
		);
	}

    //获取工作周期
    function getGzZc(){
        let _count = {}
        $NG.execServer("getInDate",{},function (res){
            console.log(`获取工作周期`,res);
            if(res.count==0)return 
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater)=>{
                updater.data.p_form_sub_cnt_m.setProps({
                    phid_cycle:{
                        label:_data.bill_name,
                        value:_data.phid
                    }
                })
            })
        })
    }
	// 计算2个日期之间得天数
	function formatDate(dateStr, outputFormat) {
		const date = new Date(dateStr);

		if (isNaN(date)) {
			return "无效的日期字符串";
		}

		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, "0");
		const day = String(date.getDate()).padStart(2, "0");
		const hours = String(date.getHours()).padStart(2, "0");
		const minutes = String(date.getMinutes()).padStart(2, "0");

		let formattedDate;

		switch (outputFormat) {
			case "yyyy-mm-dd":
				formattedDate = `${year}-${month}-${day}`;
				break;
			case "yyyy-mm-dd HH:mm":
				formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
				break;
			// 可以根据需要继续添加其他格式的处理逻辑
			default:
				formattedDate = "不支持的输出格式";
		}

		return formattedDate;
	}
    function getCntDetil(){
        console.log(mstform.getItem("u_js_type").getValue());
        // console.log(,mstform.getItem("u_js_type").getValue());
        if(!mstform.getItem("u_js_type").getValue()||!(mstform.getItem("u_js_type").getValue() == 'JSLX002')||!mstform.getItem("u_cnt_name").getValue()) return
        $NG.execServer("getCntDetail",{phid:mstform.getItem("u_cnt_name").getValue()},function (res){
            if(res.count == 0)return
            const datas = JSON.parse(res.data)
            console.log(`明细`,datas);
            dgrid1.clearRows().then(()=>{
                let  _arr = []
                _arr = []
                datas.forEach(items=>{
                    const item = items.extendObjects
                    _arr.push({
                        u_sbqd_no:item.user_u_equipment_list_no,
                        u_sbqd_name:item.user_u_equipment_list_name,
                        itemid:item.phid_itemid,
                        itemno_EXName:item.itemno,
                        itemname:item.itemname,
                        u_bqjl_qty:item.qty,
                        u_cnt_prc:item.prc_fc,
                        u_cnt_prc_vat:item.prc_vat_fc,
                        u_bqjs_amt_vat:item.amt,
                        u_tax:item.taxrate,
                        u_tax_amt:item.taxamt

                    })
                })
                dgrid1.addRows(_arr)
                dgrid1.refreshView()
            })
        })
    }
    //获取项目信息
    function getPtInfoByPhid_cnt(){
        $NG.execServer("getPtInfoByPhid_cnt",{phid_cnt:mstform.getItem("u_cnt_name").getValue()},(res)=>{
            console.log(`获取项目信息`,res);
            if(res.count === 0) return 
            const datas = JSON.parse(res.data)[0].extendObjects
            console.log(datas);
            $NG.updateState((updater)=>{
                updater.data.p_form_sub_cnt_m.setProps({
                    phid_pc:{
                        value:datas.pc_phid,
                        label:datas.pc_name
                    }
                })
            })
        })
    }
});

